package cn.kooki.app.duobao.ui.Activity.Share;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.Bean.share.NotShareGood;
import cn.kooki.app.duobao.data.Bean.share.UploadShareItem;
import cn.kooki.app.duobao.data.bus.AddShareListEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.widget.NoScrollGridView;
import cn.kooki.app.duobao.util.FileUtils;
import cn.kooki.app.duobao.util.ImageUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.TimeUtils;
import de.greenrobot.event.EventBus;

import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.ImageCaptureManager;
import me.iwf.photopicker.utils.PhotoPickerIntent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.MultipartTypedOutput;
import retrofit.mime.TypedByteArray;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;

/**
 * Created by xiong on 2016/1/1.
 */
public class AddShareActivity extends BaseNavActivity implements View.OnClickListener {
    private static final int PICK_IMAGE_CAM = 201;
    @Bind(R.id.goEditor)
    Button goEditor;
    @Bind(R.id.tips)
    ScrollView tips;
    @Bind(R.id.myTitle)
    EditText myTitle;
    @Bind(R.id.content)
    EditText content;
    @Bind(R.id.picGrid)
    NoScrollGridView picGrid;
    @Bind(R.id.txtGoodName)
    TextView txtGoodName;
    @Bind(R.id.txtSpentAmount)
    TextView txtSpentAmount;
    @Bind(R.id.txtLuckyNumber)
    TextView txtLuckyNumber;
    @Bind(R.id.txtRevealTime)
    TextView txtRevealTime;
    @Bind(R.id.submit)
    Button submit;
    @Bind(R.id.editor)
    ScrollView editor;
    private ArrayList<String> imgurls = new ArrayList<>();
    private ShareImageAdapter adapter;
    private File tempfile;
    private Uri imageuri;
    private int PICK_IMAGE = 200;
    private NotShareGood item;
    private UserInfo userinfo;
    private String path;
    private ImageCaptureManager manager;

    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.activity_addshare);
        ButterKnife.bind(this);
    }

    @Override
    protected void afterView() {
        setTitle(R.string.title_activity_addshare);
        refreshView();
        goEditor.setOnClickListener(this);
        item = getIntent().getParcelableExtra("item");
        path = Constants.APP_IMG_FOLDER_PATH.toString();
        if (!FileUtils.isFolderExist(path)) {
            FileUtils.makeDirs(path);
        }
        adapter = new ShareImageAdapter();
        picGrid.setAdapter(adapter);
        userinfo = SharePreferencesUtils.getUserinfo(this);
        picGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < imgurls.size()) {
                    imgurls.remove(position);
                    adapter.notifyDataSetChanged();
                } else {
                    pickimage();
                }
            }
        });
        if (item != null) {
            txtGoodName.setText(item.title);
            txtSpentAmount.setText(item.q_num);
            txtRevealTime.setText(TimeUtils.getTime(item.q_end_time));
            txtLuckyNumber.setText(item.q_user_code);
        }
        submit.setOnClickListener(this);
    }

    private void refreshView() {
        boolean isfirst = SharePreferencesUtils.getBoolean(this, "isfirst");
        if (!isfirst) {
            tips.setVisibility(View.GONE);
            editor.setVisibility(View.VISIBLE);
        } else {
            tips.setVisibility(View.VISIBLE);
            editor.setVisibility(View.GONE);
        }
    }

    private void pickimage() {
        new AlertDialog.Builder(this).setTitle("选择图片").setItems(new String[]{"相册", "拍照"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.i("test", which + "");
                pickerImage(which);
            }
        }).setNegativeButton("取消", null).show();
    }


    private void pickerImage(int which) {

        if (imgurls.size() < 10) {
            if (which == 0) {
                PhotoPickerIntent photoPickerIntent = new PhotoPickerIntent(this);
                photoPickerIntent.setPhotoCount(10 - imgurls.size());
                startActivityForResult(photoPickerIntent, PICK_IMAGE);
            } else {
                manager = new ImageCaptureManager(this);
                Intent intent = null;
                try {
                    intent = manager.dispatchTakePictureIntent();
                    startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            showToastMessage("最多选择10张图片");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PICK_IMAGE) {
                if (data != null) {
                    ArrayList<String> photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                    imgurls.addAll(photos);
                    adapter.notifyDataSetChanged();
                }
            }
            if (requestCode == ImageCaptureManager.REQUEST_TAKE_PHOTO) {
                if (manager != null) {
                    String url = manager.getCurrentPhotoPath();
                    imgurls.add(url);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }


    @Override
    public void onClick(View v) {
        if (v == submit) {
            UploadShare();
        }
        if (v == goEditor) {
            SharePreferencesUtils.putBoolean(this, "isfirst", true);
            refreshView();
        }
    }

    private void UploadShare() {
        if (checkForm()) {
            showLoading("正在上传中...");


            new Thread(new Runnable() {
                @Override
                public void run() {

                    UploadShareItem uitem = new UploadShareItem();
                    uitem.title = myTitle.getText().toString();
                    uitem.content = content.getText().toString();
                    uitem.shopid = item.id;
                    uitem.shopqishu = item.qishu;
                    Gson gson = new Gson();
                    String data = gson.toJson(uitem);
                    MultipartTypedOutput multipart = new MultipartTypedOutput();
                    multipart.addPart("data", new TypedString(data));
                    multipart.addPart("uname", new TypedString(userinfo.getUid()));
                    multipart.addPart("num", new TypedString(imgurls.size() + ""));
                    for (String filepath : imgurls) {

                        try {
                            Bitmap bitmap = ImageUtils.revitionImageSize(filepath);

                            tempfile = new File(path+"temp.jpg");
                            ImageUtils.compressBmpToFile(bitmap,tempfile);
                            multipart.addPart("photolist[]", new TypedFile("image/jpeg", tempfile));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    MainFactory.getApiInstance().addshare(multipart, new Callback<BaseResponse>() {
                        @Override
                        public void success(BaseResponse baseResponse, Response response) {
                            if (baseResponse.getStatus() == 0) {
                                showToastMessage("上传成功,请等待审核");
                                EventBus.getDefault().post(new AddShareListEvent());
                                finish();
                            } else {
                                showToastMessage(baseResponse.getMsg());
                            }
                            dismissLoading();
                        }

                        @Override
                        public void failure(RetrofitError error) {
                            dismissLoading();
                        }
                    });
                }
            }).start();
        }
    }

    private boolean checkForm() {
        if (TextUtils.isEmpty(myTitle.getText().toString())) {
            showToastMessage("请输入晒单主题");
            return false;
        }
        if (myTitle.getText().toString().length() < 6) {
            showToastMessage("晒单主题不得少于6个字");
            return false;
        }
        if (TextUtils.isEmpty(content.getText().toString())) {
            showToastMessage("请输入获奖感言");
            return false;
        }
        if (content.getText().toString().length() < 6) {
            showToastMessage("获奖感言不得少于30字");
            return false;
        }
        if (imgurls.size() == 0) {
            showToastMessage("请选择至少一张图片");
            return false;
        }
        return true;
    }

    class ShareImageAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (imgurls.size() < Constants.MAX_IMGCOUNT) {
                return imgurls.size() + 1;
            } else {
                return imgurls.size();
            }
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(AddShareActivity.this).inflate(R.layout.layout_add_shareitem, parent, false);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            if (position < imgurls.size()) {
                Glide.with(AddShareActivity.this).load(imgurls.get(position)).centerCrop().placeholder(R.drawable.bg_add_pic).into(viewHolder.imageView);
            } else {
                Glide.with(AddShareActivity.this).load(R.drawable.bg_add_pic).into(viewHolder.imageView);
            }

            return convertView;
        }

        /**
         * This class contains all butterknife-injected Views & Layouts from layout file 'layout_add_shareitem.xml'
         * for easy to all layout elements.
         *
         * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
         */
        class ViewHolder {
            @Bind(R.id.imageView)
            ImageView imageView;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }

}
